//
//  HomeVC.swift
//  ShareUmbrella
//
//  Created by niupark on 2017/8/5.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import SWRevealViewController
import RxSwift
import CoreLocation
import TSMessages
import SwiftyJSON


class StatusView: YSView {
    private var opaqueAnimate: CABasicAnimation!
    var action: (()->Void)?
    let titleLabel = UILabel()
    override func setup() {
        super.setup()
        self.backgroundColor = .red
        self.opaqueAnimate = CABasicAnimation(keyPath: "opacity")
        opaqueAnimate.fromValue = 1
        opaqueAnimate.toValue = 0.3
        opaqueAnimate.autoreverses = true
        opaqueAnimate.repeatCount = MAXFLOAT
        opaqueAnimate.duration = 0.8
        /////添加tapGuestureRecognizer手势
        let tapGR = UITapGestureRecognizer(target: self, action: #selector(tapHandler))
        self.addGestureRecognizer(tapGR)
        self.titleLabel.ys.customize { (view) in
            self.addSubview(view)
            view.textColor = .white
            view.font = YSFont.t04.font
            view.snp.makeConstraints({ (make) in
                make.center.equalTo(self)
            })
        }
        
    }
    //////手势处理函数
    func tapHandler(sender:UITapGestureRecognizer) {
        ///////todo....
        self.action?()
    }

    func startAnimation(){
        self.titleLabel.layer.add(opaqueAnimate, forKey: "opacityAnimate")

    }
    func stopAnimation(){
        self.titleLabel.layer.removeAnimation(forKey: "opacityAnimate")
    }
}

class HomeVC: MapViewVC {
    
    
    var btnMenu = UIButton()
    var btnHelper = UIButton()
    var btnRecipients = UIButton()
    
    var arrForUsers = NSMutableArray()
    var statusView:StatusView?
    var maskImage: UIImageView!
    override func setup() {
        super.setup()
        self.showCustomNavigationBar = true
    }
    
    override func customNavigationConfig(_ config: YSNavagtionConfig) {
        config.backImage = "列表icon"
    }
    
    /*
     *
     * 界面布局初始化
     */
    override func buildUI() {
        super.buildUI()

        
        self.revealViewController()!.revealToggle(nil)

        self.title = I18n("VC.home.title")
        let revealController = self.revealViewController()!
        self.view.addGestureRecognizer(revealController.panGestureRecognizer())
        
        
        self.maskImage = UIImageView(frame: self.view.bounds).ys.customize { (view) in
            self.view.addSubview(view)
            view.image = UIImage(named:"背景虚化")
            view.isHidden = true
        }
        btnMenu.ys.customize { (view) in
            view.setBackgroundImage(UIImage(named: "按钮框"), for: .normal)
            self.view.addSubview(view)
            view.snp.makeConstraints({ (make) in
                make.centerX.equalTo(self.view.snp.centerX)
                make.bottom.equalTo(self.view.snp.bottom).offset(-50)
            })
        }
        
        let _ = UIImageView(frame: .zero).ys.customize { (view) in
            view.image = UIImage(named: "备雨伞")
            btnMenu.addSubview(view)
            view.snp.makeConstraints({ (make) in
                make.center.equalTo(self.btnMenu)
            })
        }
        _ = btnMenu.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                
                guard let `self` = self  else {
                    return
                }
                self.showMenu(self.btnHelper.isHidden)
        })
    
        btnHelper.ys.customize { (view) in
            view.layer.cornerRadius = 20
            view.layer.masksToBounds = true
            view.isHidden = true
            view.ys.setImageAndTitle(imageName: "搜索", title: "求助他人", type: .left, space: 2.0)
            self.view.addSubview(view)
            view.backgroundColor = UIColor(colorLiteralRed: 65/255.0, green: 181/255.0, blue: 116/255.0, alpha: 1)
    
            view.snp.makeConstraints({ (make) in
                make.centerX.equalTo(self.btnMenu)
                make.bottom.equalTo(self.btnMenu.snp.top).offset(-30)
                make.width.equalTo(150)
                make.height.equalTo(40)
            })
        }
        
        
        _ = btnHelper.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                
                let vc = HelperVC()
                
                self?.ys.push(vc)
            })
        
        
        btnRecipients.ys.customize { (view) in
            view.layer.cornerRadius = 20
            view.layer.masksToBounds = true
            view.ys.setImageAndTitle(imageName: "分享icon", title: "伸出援手", type: .left, space: 2.0)
            view.isHidden = true
            view.backgroundColor = UIColor(colorLiteralRed: 65/255.0, green: 181/255.0, blue: 116/255.0, alpha: 1)
            self.view.addSubview(view)
            
            view.snp.makeConstraints({ (make) in
                make.centerX.equalTo(self.btnMenu)
                make.bottom.equalTo(self.btnHelper.snp.top).offset(-30)
                make.width.equalTo(150)
                make.height.equalTo(40)
            })
            
        }
        
        "abc".rx.base.trimmingCharacters(in: CharacterSet.whitespaces)
        _ = btnRecipients.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                
                let vc = RecipientsVC()

                self?.ys.push(vc)
                
//                let vc = RecipientsResultVC()
//
//                self?.ys.push(vc)

            })
    }
    
    func  showMenu(_ show: Bool) {
        var showAlpha = 0.0

        if show {
            showAlpha = 1.0
            self.btnHelper.isHidden = false
            self.btnRecipients.isHidden = false
            self.maskImage.isHidden = false
        }
        UIView.animate(withDuration: 1.0, animations: {
            self.btnHelper.alpha = CGFloat(showAlpha)
            self.btnRecipients.alpha = CGFloat(showAlpha)
            self.maskImage.alpha = CGFloat(showAlpha)
        }, completion: { (Bool) in
            if showAlpha == 0.0 {
                self.btnHelper.isHidden = true
                self.btnRecipients.isHidden = true
                self.maskImage.isHidden = true
            }

        })
    }
    
    override func actionBack() {
        
        let revealController = self.revealViewController()!
    
        revealController.revealToggle(nil)

    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.statusView?.stopAnimation()
        

    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.statusView?.startAnimation()
        MessageReceiver.shared.listenNotification()
    }
    //
    override func buildRx() {
        super.buildRx()
        self.nearbyUserType = .allUser
        //监听用户登录操作
        _  = Auth.isLogin.asObservable().takeUntil(self.rx.deallocated).subscribe(onNext: { [weak self] (isLogin) in
            guard let `self` = self else {
                return
            }
            self.destoryStatusView()
            
        })

    

    }
    
    func createStatusView(title: String, action: @escaping()->Void) {
        guard let statusView = self.statusView else {
            self.statusView = StatusView().ys.customize({ (view) in
                self.view.addSubview(view)
                view.titleLabel.text = title
                view.snp.makeConstraints({ (make) in
                    make.top.equalTo(self.view).offset(64)
                    make.leading.trailing.equalTo(self.view)
                    make.height.equalTo(50)
                })
                view.action = action
                self.view.bringSubview(toFront: view)
            })
            self.statusView?.startAnimation()
            return
        }
        statusView.titleLabel.text = title
        statusView.action = action
        statusView.bringSubview(toFront: view)
    }
    func destoryStatusView(){
        guard let sView = self.statusView else {
            return
        }
        sView.removeFromSuperview()
        self.statusView = nil
    }
    
    //用户状态处理
   override func handleStatusChange(statusInfo: StatusInfo) {
    
        switch statusInfo.status {
        case .normal:
            //正常
            self.btnMenu.isHidden = false
            self.destoryStatusView()
        case .accepting, .accepted:
            self.showMenu(false)
            self.btnMenu.isHidden = true
            self.createStatusView(title: statusInfo.status.tipsString) {[weak self] in
                
                let vc = RecipientsVC()
                
                self?.ys.push(vc)

            }

        case .waiting, .beAccepted:
            self.showMenu(false)
            self.btnMenu.isHidden = true
            self.createStatusView(title: statusInfo.status.tipsString) {[weak self] in
                
                let vc = HelperVC()
                
                self?.ys.push(vc)
                
            }
        case .inTrip:
            if User.statusInfo.value!.info["role"].intValue == 0 { //求助者
                self.showMenu(false)
                self.btnMenu.isHidden = true
                self.createStatusView(title: statusInfo.status.tipsString) {[weak self] in
                    
                    let vc = HelperVC()
                    
                    self?.ys.push(vc)
                    
                }
            }else{
                self.showMenu(false)
                self.btnMenu.isHidden = true
                self.createStatusView(title: statusInfo.status.tipsString) {[weak self] in
                    
                    let vc = RecipientsVC()
                    
                    self?.ys.push(vc)
                    
                }
            }
        }
        


    }
    
}


